package com.itbaizhan.dao.impl;

import com.itbaizhan.common.JdbcDruidUtil;
import com.itbaizhan.dao.BaseDao;
import com.itbaizhan.exception.ApplicationException;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.List;

public class BaseDaoImpl implements BaseDao {

    @Override
    public int executeUpdate(String sql, Object[] param) {
        Connection conn=null;
        PreparedStatement ps=null;
        int row=0;
        try{
            conn= JdbcDruidUtil.getConnection();
            ps=conn.prepareStatement(sql);
            ParameterMetaData pd = ps.getParameterMetaData();
            for(int i=0;i<pd.getParameterCount();i++){
                ps.setObject(i+1,param[i]);

            }
            row=ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
JdbcDruidUtil.closeResource(ps,conn);
        }
        return row;
    }

    @Override
    public <T> List<T> select(String sql, Object[] param, Class<T> clazz) {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<T> list=null;
        try{
            conn=JdbcDruidUtil.getConnection();
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();
            ParameterMetaData pd=ps.getParameterMetaData();
            for(int i=0;i<pd.getParameterCount();i++){
                ps.setObject(i+1,param[i]);

            }
            rs=ps.executeQuery();
            ResultSetMetaData rm =rs.getMetaData();
            while(rs.next()){
                T bean=clazz.newInstance();
                for(int i=0;i<rm.getColumnCount();i++){
                    String columnName=rm.getColumnName(i+1);
                    Object value=rs.getObject(columnName);
                    BeanUtils.setProperty(bean,columnName,value);
                }
                list.add(bean);

            }



        }catch (Exception e ){
            e.printStackTrace();
            throw new ApplicationException(e.getMessage());
        }finally{
            JdbcDruidUtil.closeResource(rs,ps,conn);

        }
        return list;


    }
}
